from nameko.rpc import rpc
from nameko.timer import timer
import logging as logger

import json
import time

import websocket
import threading


"""
通过websocket方式可获取实时数据及报警信息
"""


class data_websocket(websocket.WebSocketApp):
    def __init__(self, url=None, timeinterval=5):
        self.timeinterval = timeinterval
        self.heartbeat = None
        super(data_websocket, self).__init__(url=url,on_open=self.on_open,on_message=self.on_message,
                                             on_error=self.on_error,on_close=self.on_close)

    def on_message(self, message):
        if message.count("@#$") > 4:  # 获取报警窗口（实时报警信息）
            try:
                alert_time, alert_point, alert_name, alert_script, \
                alert_action, alert_voice, alert_type, alert_value = message.split("@#$")
            except:
                return
            """判断报警点及报警类型，通过RPC接口执行相关操作"""
            # with ClusterRpcProxy(config) as cluster_rpc:
            # hdatas = cluster_rpc.control_service.grid_control_fun.call_async()
            print(message)

        elif message.startswith("20150014"):  # 获取报警持续状态信息
            alert_info = (message.split("[")[1]).split("]")[0]
            alert_info = json.loads(alert_info) if alert_info else message
            print(alert_info)

        elif message.startswith("20150002") and message.find("[9]")>0:  # 实时数据返回
            data = message.split("[9]")[1]
            """返回的实时数据值（频率每秒一次），通过RPC接口执行相关操作"""
            print(data)
            # with ClusterRpcProxy(config) as cluster_rpc:
            #     hdatas = cluster_rpc.scada_service.get_histrydatas.call_async()

        elif message.startswith("20150010") and message.find("[8]") > 0:  # 设定值结果返回，0失败，1成功
            data = message.split("[8]")[1]

    def on_error(self, error):
        logger.info("Websocket error")

    def on_close(self):
        self.heartbeat.cancel()
        logger.info("Websocket closed !!")

    def on_open(self):
        def run():
            self.send("201500110000")  # 心跳报文，超过10s(获取实时值)、20s(获取报警信息)服务器断开链路
            self.heartbeat = threading.Timer(self.timeinterval, run)
            self.heartbeat.start()
        self.heartbeat = threading.Timer(self.timeinterval, run)
        self.heartbeat.start()
        # file = open("cyc.log", "w")
        # file.write("123\n")
        # file.close()
